//
//  ZWNetWorwTool.swift
//  张伟的微博
//
//  Created by 伟 on 16/2/28.
//  Copyright © 2016年 伟. All rights reserved.
//

import UIKit
import AFNetworking
enum ZWNetWorwToolError: Int {
    case AccessTokenEmpty = -1
    case UidEmpty = -2
    var errorMessage:String {
        get {
            switch self {
                case AccessTokenEmpty: return "AccessToken没有值"
                case UidEmpty: return "Uid没有值"
            }
        }
    }
    func error()->NSError {
        return NSError(domain: "www.zhangwei.com", code: self.rawValue, userInfo: ["errorMessage":self.errorMessage])
    }
}



class ZWNetWorwTool: NSObject {
    
    static let sharedInstance :ZWNetWorwTool = ZWNetWorwTool()
    let afnManger : AFHTTPSessionManager
    
    private override init() {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        afnManger = AFHTTPSessionManager(baseURL: baseURL)
        afnManger.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
    }
    
    let client_id = "980671925"
    let redirect_uri = "http://www.baidu.com/"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    func oauthLoginUrl() -> NSURL {
        let oauthString = oauthUrl+"?"+"client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
     
        return NSURL(string: oauthString)!
        
    }
    func getAccesstoken(code:String,accessTokenFinished:NetFinishedCallBack) {
    
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id" :"980671925",
            "client_secret" :"c3171d4de50271705a553fd902fcc914",
            "grant_type" :"authorization_code",
            "code" :code,
            "redirect_uri":redirect_uri
        ]
        afnManger.POST(urlstring, parameters: parameters, progress: nil, success: { (_, response) -> Void in
//              print("AccessToken获得成功:\(response)")
            let dic = response as? [String: AnyObject]
            accessTokenFinished(result: dic, error: nil)
            }) { (_, error) -> Void in
//              print("AccessToken获得成功:\(error)")
                accessTokenFinished(result: nil, error: error)

        }
    }
    
    func loadUserInfo(finshed:NetFinishedCallBack) {
        //判断acce_token
        //绑定守卫acces_token可以在代码后面直接使用
        guard let access_token = ZWUserAccountViewModel.sharedInstance.userAccount?.access_token else
        {
            let error = ZWNetWorwToolError.AccessTokenEmpty.error()
            finshed(result: nil, error: error)
            return
        }
        //判断Uid
        guard let uid = ZWUserAccountViewModel.sharedInstance.userAccount?.uid else {
        
            let error = ZWNetWorwToolError.UidEmpty.error()
            finshed(result: nil, error: error)
            return
        }
        //准备发送 acces_token和Uid 给服务器，获得用户信息
        let urlstring = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token":access_token,"uid":uid]
        //AFN 通过get
        
        afnManger.GET(urlstring, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            finshed(result: result as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                 finshed(result: nil, error: error)
        }
       
        
    }
    /**
    *  获取当前登录用户及其所关注（授权）用户的最新微博
    */
    func loatStatus(finshed: NetFinishedCallBack){
       let count = 1
        let parmeters = ["count":count]
       let usrlstring = "https://api.weibo.com/2/statuses/home_timeline.json"
        requestGET(usrlstring, parameters: parmeters, finshed: finshed)
        
    }
    
    //封装AFN的GET请求方式
    func requestGET(urlstring:String,var parameters:[String: AnyObject]?,finshed:NetFinishedCallBack) {
    
        guard let access_token = ZWUserAccountViewModel.sharedInstance.userAccount?.access_token else{
            let error = ZWNetWorwToolError.AccessTokenEmpty.error()
            finshed(result: nil, error: error)
            return
        }
        //判断传入的parameters是否为空，为空就为他创建一个字典
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        //直接将accesstoken给parameters  有的话就不会创建，没有会创建
        parameters!["access_token"] = access_token
        
        afnManger.GET(urlstring, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            finshed(result: result as? [String:AnyObject], error: nil)
            }) { (_, error) -> Void in
                finshed(result: nil, error: error)
        }
        
    }
    typealias NetFinishedCallBack = ((result:[String: AnyObject]?,error:NSError?)->())

}
